package com.bea.ftd.routing.filter;


import com.bea.ftd.common.model.MappingResponse;
import com.bea.ftd.common.model.MsgInRequest;
import com.bea.ftd.common.model.MsgOutResponse;
import com.bea.ftd.routing.feign.MappingFeign;
import com.google.gson.Gson;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.http.HttpServletRequestWrapper;
import com.netflix.zuul.http.ServletInputStreamWrapper;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.util.StreamUtils;

import javax.annotation.Resource;
import javax.servlet.ServletInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.netflix.zuul.context.RequestContext.getCurrentContext;

/**
 * 报文转换过滤器
 * */
public class MsgMappingFilter extends AbstractZuulFilter {


    @Resource
    MappingFeign mappingFeign;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 4;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext context = getCurrentContext();

        if(context.get("needMapping")!=null&&!(boolean)context.get("needMapping")){
            return false;
        }else{
            if(context.get("isSuccess")!=null){
                return (boolean)context.get("isSuccess");
            }else{
                return false;
            }

        }
    }

    @Override
    public Object run() {
        RequestContext context = getCurrentContext();
        try {
            logger.info("===========>开始报文转换");


            InputStream stream = context.getRequest().getInputStream();
            String body = StreamUtils.copyToString(stream, Charset.forName("UTF-8"));
            logger.info(body);
            Map<String, Object> map = new HashMap<String, Object>();
            map = new Gson().fromJson(body,map.getClass());
            MsgInRequest msgInRequest = new MsgInRequest();
            msgInRequest.setApiId(context.get("apiId").toString());
            msgInRequest.setMsgOutType(context.get("msgOutType").toString());
            msgInRequest.setData(map);
            msgInRequest.setPartnerCode(context.get("partnerCode").toString());
            MsgOutResponse msgOutResponse = mappingFeign.transMsg(msgInRequest);
            if (msgOutResponse.getErrorCode()==0){
                final byte[] reqBodyBytes = msgOutResponse.getData().getBytes("utf-8");
                context.setRequest(new HttpServletRequestWrapper(getCurrentContext().getRequest()) {
                    @Override
                    public ServletInputStream getInputStream() throws IOException {
                        return new ServletInputStreamWrapper(reqBodyBytes);
                    }

                    @Override
                    public int getContentLength() {
                        return reqBodyBytes.length;
                    }

                    @Override
                    public long getContentLengthLong() {
                        return reqBodyBytes.length;
                    }
                });
            }else{
                context.setSendZuulResponse(false); //不对其进行路由
                context.setResponseStatusCode(403);
                context.getResponse().setCharacterEncoding("utf-8");
                context.setResponseBody("data mapping error:\n"+msgOutResponse.getErrorMsg());
                context.set("isSuccess", false);
            }
        }catch (Exception e){
            e.printStackTrace();
            context.setSendZuulResponse(false); //不对其进行路由
            context.getResponse().setCharacterEncoding("utf-8");
            context.setResponseStatusCode(403);
            context.setResponseBody("data mapping error:\n"+e.getMessage());
            context.set("isSuccess", false);
        }
        return null;
    }

}
